Page({
  data: {
    active: 0,
    orderList: [],
    allOrders: [],
    loading: false,
    error: null,
    pageSize: 10,
    pageNum: 1,
    hasMore: true,
    hotelId: "",
    tabStatusMap: {
      0: 'all',
      1: 'pending_usage',
      2: 'pending_review',
      3: 'reviewed',
      4: 'refunded'
    },
    // 新增状态数字到文字的映射
    statusNumberMap: {
      '1': '待使用',
      '2': '待评价',
      '3': '已评价',
      '4': '已退款'
    }
  },

  onLoad() {
    this.checkLoginStatus();
  },

  checkLoginStatus() {
    // 跳过登录检查，直接获取数据
    this.initData();
  },

  // 初始化数据
  initData() {
    const app = getApp();
    if (!app.globalData.userInfo?.userId) {
      this.setData({
        error: '请先登录获取用户信息',
        loading: false
      });
      return;
    }

    // 确保 userId 正确赋值
    app.globalData.userId = app.globalData.userInfo.userId;

    this.setData({ loading: true });
    this.fetchAllOrders().then(() => {
      this.setData({
        orderList: this.filterOrdersByStatus('all'),
        loading: false
      });
    }).catch(err => {
      console.error('初始化数据失败:', err);
      console.log('错误详情:', JSON.stringify(err, null, 2)); // 打印详细错误信息
      this.setData({
        error: err.message || '加载失败',
        loading: false
      });
    });
  },

  // 获取所有订单数据
  fetchAllOrders() {
    return new Promise((resolve, reject) => {
      Promise.all([
        this.fetchOrders('/system/infos/list1').then(data => {
          console.log('景点门票订单数据:', data);
          return data.map(item => ({ ...item, source: '景点门票', scenicId: item.aid || null }));
        }),
        // 酒店订单（修改后）
        this.fetchOrders('/system/orders/list').then(data => {
          // 确保 data 是数组，遍历提取 hotelId
          const hotelOrders = data.map(item => {
            // 假设每个酒店订单有 hotelId 字段
            const hotelId = item.hotelId || null; 
            return { ...item, source: '酒店', hotelId }; // 新增 hotelId 到订单对象
          });
          console.log('酒店订单数据（含 hotelId）:', hotelOrders);
          return hotelOrders; // 返回处理后的数组
        }),
        this.fetchOrders('/system/resorder/list').then(data => {
          console.log('餐馆订单数据:', data);
          return data.map(item => ({ ...item, source: '餐馆', resId: item.resId || null }));
        })
      ]).then(results => {
        console.log('三种订单数据获取成功:', results);
        const allOrders = [].concat(...results).map(order => {
            const formattedOrder = this.formatOrderData(order);
            console.log('格式化后的订单数据:', formattedOrder);
            return formattedOrder;
        });
        
        const ordersNeedImages = allOrders.filter(order => order.needFetchImage);
        console.log('需要获取图片的订单:', ordersNeedImages);
        
        if (ordersNeedImages.length > 0) {
            this.fetchImagesForOrders(ordersNeedImages)
                .then(() => {
                    console.log('图片获取完成后的订单数据:', allOrders);
                    this.setData({ allOrders });
                    resolve();
                })
                .catch(err => {
                    console.error('获取图片失败:', err);
                    this.setData({ allOrders });
                    resolve(); // 即使图片获取失败也继续
                });
        } else {
            this.setData({ allOrders });
            resolve();
        }
    }).catch(err => {
        console.error('获取订单数据失败:', err);
        reject(err);
    });
});
},
// 新增方法：为订单获取图片
fetchImagesForOrders(orders) {
  const promises = orders.map(order => {
    if (order.source === '酒店' && order.hotelId) {
      return this.fetchHotelImage(order.hotelId).then(imageUrl => {
        order.image = imageUrl;
      });
    } else if (order.source === '餐馆' && order.resId) {
      return this.fetchRestaurantImage(order.resId).then(imageUrl => {
        order.image = imageUrl;
      });
    }
    return Promise.resolve();
  });
  
  return Promise.all(promises);
},

// 新增方法：获取酒店图片
fetchHotelImage(hotelId) {
  return new Promise((resolve) => {
      wx.request({
          url: `http://localhost:8080/system/f_details/${hotelId}`,
          method: 'GET',
          success: (res) => {
              console.log('酒店详情响应:', res);
              if (res.data.code === 200 && res.data.data) {
                  // 检查响应数据结构，从 miaoshutupian 字段获取图片 URL
                  const imageUrl = res.data.data.miaoshutupian || '/assets/hotel-default.png';
                  console.log('获取到的酒店图片URL:', imageUrl);
                  resolve(imageUrl);
              } else {
                  console.warn('酒店详情接口返回数据格式不正确');
                  resolve('/assets/hotel-default.png');
              }
          },
          fail: (err) => {
              console.error('获取酒店图片失败:', err);
              resolve('/assets/hotel-default.png');
          }
      });
  });
},

fetchRestaurantImage(resId) {
  return new Promise((resolve) => {
      wx.request({
          url: `http://localhost:8080/system/resinfo/${resId}`,
          method: 'GET',
          success: (res) => {
              console.log('餐馆详情响应:', res);
              if (res.data.code === 200 && res.data.data) {
                  // 检查响应数据结构，从 imgUrl 字段获取图片 URL
                  const imageUrl = res.data.data.imgUrl || '/assets/restaurant-default.png';
                  console.log('获取到的餐馆图片URL:', imageUrl);
                  resolve(imageUrl);
              } else {
                  console.warn('餐馆详情接口返回数据格式不正确');
                  resolve('/assets/restaurant-default.png');
              }
          },
          fail: (err) => {
              console.error('获取餐馆图片失败:', err);
              resolve('/assets/restaurant-default.png');
          }
      });
  });
},

  // 格式化订单数据
  formatOrderData(order) {
    // 统一不同订单类型的字段名
    const sourceTypeMap = {
      '景点门票': 'info',
      '酒店': 'order',
      '餐馆': 'resorder'
    };
    // 根据订单类型设置默认图片
  let defaultImage = '/assets/default.png';
  if (order.source === '酒店') {
    defaultImage = '/assets/hotel-default.png';
  } else if (order.source === '餐馆') {
    defaultImage = '/assets/restaurant-default.png';
  }
  
    const formatted = {
      needFetchImage: !order.image && (order.hotelId || order.resId),
      id: order.id || order.orderId,
      name: order.hotelName || order.title || order.resName,
      status: this.mapStatus(order.status || order.state),
      orderNo: order.orderNumber || order.id || order.orderId,
      orderTime: order.orderTime || order.donetime || order.bookingtime,
      totalPrice: `¥${order.price || order.paymentAmount || order.totalPrice}`,
      image: order.image || defaultImage, // 使用类型特定的默认图片
      showEvaluateBtn: (order.status || order.state) === '已使用',
      source: order.source, // 保留订单来源
      sourceType: sourceTypeMap[order.source] || 'unknown', // 添加后端接口类型标识
      
      // 新增：保留业务ID字段
      hotelId: order.hotelId || '',       // 酒店ID
      resId: order.resId || '',           // 餐馆ID
      scenicId: order.scenicId || ''      // 景点ID
    };
  
    // 添加特定类型订单的额外字段
    if (order.hotelName) {
      formatted.roomType = order.roomType;
      formatted.timeRange = order.timeRange;
  }
  
    return formatted;
  },

  // 映射订单状态
  mapStatus(status) {
    const statusMap = {
      '1': '待使用',
      '2': '待评价',
      '3': '已评价',
      '4': '已退款',
      '已使用': '已使用',
      '待使用': '待使用',
      '待付款': '待付款',
      'refund': '退款/售后',
      'pending_payment': '待付款',
      'pending_usage': '待使用',
      'pending_review': '待评价',
      'reviewed': '已评价',
      'refunded': '已退款'
    };
    return statusMap[status] || status;
  },

  // 通用请求方法
  fetchOrders(url) {
    const app = getApp(); // 获取 App 实例
    const userId = app.globalData.userId; // 获取user_id

    // 检查 userId 是否存在
    if (!userId) {
      return Promise.reject('用户 ID 不存在');
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: `http://localhost:8080${url}?userId=${userId}`, // 添加userId参数
        method: 'GET',
        header: {
          Authorization: app.globalData.token
        },
        success(res) {
          console.log(`请求 ${url} 的响应状态码:`, res.statusCode);
          console.log(`请求 ${url} 的响应数据:`, res.data);
          if (res.statusCode === 200 && res.data.code === 200) {
            resolve(res.data.rows || []);
          } else {
            reject(res.data.msg || '请求失败');
          }
        },
        fail(err) {
          console.log(`请求 ${url} 失败:`, err);
          reject('网络错误');
        }
      });
    });
  },

  // 根据状态过滤订单
  filterOrdersByStatus(statusType) {
    const { allOrders } = this.data;
    return allOrders.filter(order => {
      switch (statusType) {
        case 'all':
          return true;
        case 'pending_payment':
          return order.status === '待付款';
        case 'pending_usage':
          return order.status === '待使用';
        case 'pending_review':
          return order.status === '待评价';
        case 'reviewed':
          return order.status === '已评价';
        case 'refunded':
          return order.status === '已退款';
        default:
          return true;
      }
    });
  },

  // 处理标签页切换
  onTabChange(event) {
    const { index } = event.detail;
    const statusType = this.data.tabStatusMap[index];

    this.setData({
      active: index,
      orderList: this.filterOrdersByStatus(statusType)
    });
  },

  // 去评价页面
  onEvaluate(event) {
    const order = this.getOrderByIndex(event);
    this.navigateToEvaluationPage(order);
  },

  // 去使用（核销）
  onUseOrder(event) {
    const order = this.getOrderByIndex(event);
    this.navigateToQrCodePage(order);
  },

  // 点击订单跳转到订单详情页
  onOrderDetail(event) {
    const order = this.getOrderByIndex(event);
    this.navigateToOrderDetailPage(order);
  },

  // 取消订单
  onCancelOrder(event) {
    const order = this.getOrderByIndex(event);
    this.showCancelOrderModal(order);
  },

  // 根据索引获取订单
  getOrderByIndex(event) {
    const index = event.currentTarget.dataset.index;
    return this.data.orderList[index];
  },

  // 跳转到评价页
  navigateToEvaluationPage(order) {
    const hotelId = order.hotelId || ''; 
    const resId = order.resId || ''; 
    const scenicId = order.scenicId || ''; 

    wx.navigateTo({
      url: `/pages/order_evaluation/order_evaluation?orderId=${order.id}` +
        `&orderName=${encodeURIComponent(order.name)}` +
        `&orderNo=${encodeURIComponent(order.orderNo)}` +
        `&sourceType=${encodeURIComponent(order.source)}` +
        `&hotelId=${encodeURIComponent(hotelId)}` + 
        `&resId=${encodeURIComponent(resId)}` + 
        `&scenicId=${encodeURIComponent(scenicId)}`
    });
  },

  // 跳转到核销页
navigateToQrCodePage(order) {
  wx.navigateTo({
    url: `/pages/qrcode/qrcode?` +
      `orderId=${order.id}` +
      `&title=${encodeURIComponent(order.name)}` +
      `&image=${encodeURIComponent(order.image)}` +
      `&price=${order.totalPrice}` +
      `&count=1` +
      `&source=${encodeURIComponent(order.source)}` +
      `&sourceType=${encodeURIComponent(order.sourceType)}`
  });
},

  // 跳转到订单详情页
  navigateToOrderDetailPage(order) {
    const app = getApp();
    wx.showLoading({ title: '加载中...' });

    const sourceTypeMap = {
      'info': 'infos',
      'order': 'orders',
      'resorder': 'resorder' 
    };

    const apiUrl = `http://localhost:8080/system/${sourceTypeMap[order.sourceType]}/${order.id}`;

    console.log('请求的API URL:', apiUrl); 

    wx.request({
      url: apiUrl,
      method: 'GET',
      header: {
        Authorization: app.globalData.token
      },
      success: (res) => {
        wx.hideLoading();
        console.log('API响应:', res); 
        if (res.data.code === 200) {
          const detailData = res.data.data || res.data;
          wx.navigateTo({
            url: `/pages/order_details/order_details?data=${encodeURIComponent(JSON.stringify({
              ...detailData,
              sourceType: order.sourceType,
              formattedData: order
            }))}`
          });
        } else {
          wx.showToast({ title: '获取详情失败', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('API请求失败:', err); 
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 显示取消订单确认框
  showCancelOrderModal(order) {
    wx.showModal({
      title: '确认取消订单',
      content: '确定要取消该订单并发起退款吗？',
      success: (res) => {
        if (res.confirm) {
          this.cancelOrder(order);
        }
      }
    });
  },

  // 取消订单
  cancelOrder(order) {
    let url = '';
    let data = {};
    // 根据订单类型选择对应的接口
    if (order.source === '景点门票') {
      url = 'http://localhost:8080/system/infos';
      data = {
        id: order.id,
        state: '4' 
      };
    } else if (order.source === '酒店') {
      url = 'http://localhost:8080/system/orders';
      data = {
        orderId: order.id,
        status: '4' 
      };
    } else if (order.source === '餐馆') {
      url = 'http://localhost:8080/system/resorder';
      data = {
        orderId: order.id,
        status: '4'
      };
    }

    if (url) {
      const app = getApp();
      wx.request({
        url: `${url}/`, 
        method: 'PUT',
        header: {
          'Content-Type': 'application/json',
          Authorization: app.globalData.token
        },
        data: data,
        success: (response) => {
          if (response.data.code === 200) {
            // 更新前端订单状态
            const allOrders = this.data.allOrders.map(o => {
              if (o.id === order.id) {
                return {
                  ...o,
                  status: '已退款'
                };
              }
              return o;
            });
            this.setData({
              allOrders,
              orderList: this.filterOrdersByStatus(
                this.data.tabStatusMap[this.data.active]
              )
            });
            wx.showToast({
              title: '订单已取消，退款成功',
              icon: 'success'
            });
          } else {
            wx.showToast({
              title: response.data.msg || '退款失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });
    }
  }
});